package com.peng.leetcode.search.binarysearch;

/**
 * SearchMatrix
 * 74. 搜索二维矩阵
 * https://leetcode.cn/problems/search-a-2d-matrix/
 *
 * 先使用二分查找在二维数组中第一列找到最后一个小于等于给定元素的索引位置
 * 在这个索引对应的数组中进行二分查找
 * m*n的矩阵 时间复杂度 m + log(m) + log(n)
 *
 * @author: lupeng6
 * @create: 2023/3/9 20:25
 */
public class SearchMatrix {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) {
            return false;
        }
        int[] arr = new int[matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            arr[i] = matrix[i][0];
        }
        int i = searchLastLE(arr, target);
        if (i == -1) {
            return false;
        }
        System.out.println(i);
        // search
        int l = 0;
        int r = matrix[i].length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (matrix[i][mid] == target) {
                return true;
            }
            if (matrix[i][mid] < target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return false;
    }

    /**
     * 搜索最后一个小于等于给定元素的index
     *
     * @author lupeng6
     * @date 2023/3/9 20:27
     */
    private int searchLastLE(int[] nums, int target) {
        int l = 0;
        int r = nums.length;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] <= target) {
                if (mid == (nums.length - 1) || nums[mid + 1] > target) {
                    return mid;
                } else {
                    l = mid + 1;
                }
            } else {
                r = mid - 1;
            }
        }
        return -1;
    }
}
